{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 作业B \n",
    "## API信息\n",
    "终结点: https://westcentralus.api.cognitive.microsoft.com/face\n",
    "\n",
    "密钥 1: d4059f977ae540cb85963ef89c95599d\n",
    "\n",
    "密钥 2: 73082cc9c6514f0ab0f1804ae3d64ce3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 作业要求\n",
    "* 选取3家人脸识别API，每家API实现3张照片（1张单人、2张多人），比较算出來的年纪、性別及情绪內容并做出这3家API不同之处的结论，【总成绩+2.5分】\n",
    "* 最少需做1家人脸识别API，并实现3张照片（1张单人、2张多人）的年纪、性别及情绪，【少于1家总成绩-1分】\n",
    "* 提交HTML档，命名为【姓名-X家API-学号】"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 作业部分 第一家API（AZURE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第一张：单人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': '55b27deb-d55d-4d92-97f1-65435fd06623',\n",
       "  'faceRectangle': {'top': 527, 'left': 437, 'width': 335, 'height': 335},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 19.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.0,\n",
       "    'neutral': 0.999,\n",
       "    'sadness': 0.001,\n",
       "    'surprise': 0.0}}}]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "KEY = 'd4059f977ae540cb85963ef89c95599d'  # Replace with a valid Subscription Key here.\n",
    "# Base URL,  Request URL中 符号?以前\n",
    "#。                          eastasia.api.cognitive.microsoft.com  ==》{endpoint}\n",
    "BASE_URL = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect' # 人脸检测\n",
    "\n",
    "# 沿用API的示范代碼，{subscription key}用KEY代入\n",
    "HEADERS = {\n",
    "    # Request headers\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': '{}'.format(KEY), #''  \n",
    "}\n",
    "\n",
    "img_url = 'http://liuyu19.gitee.io/api/img/1.jpg'\n",
    "\n",
    "data = {\n",
    "    'url': '{}'.format(img_url),\n",
    "}\n",
    "payload = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'flase',\n",
    "    'returnFaceAttributes': '{}'.format('age,gender,emotion'), \n",
    "}\n",
    "r = requests.post(BASE_URL,data=json.dumps(data),params = payload,headers=HEADERS)\n",
    "r.status_code\n",
    "results = r.json()\n",
    "results\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第二张：多人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': 'ba14a02d-2d14-4773-85d3-9bdf7ebaa648',\n",
       "  'faceRectangle': {'top': 118, 'left': 144, 'width': 88, 'height': 88},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 18.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.003,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.813,\n",
       "    'neutral': 0.184,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': '4bf7c0dd-02b1-45ba-a148-7442fdca3344',\n",
       "  'faceRectangle': {'top': 117, 'left': 376, 'width': 64, 'height': 64},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 20.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.001,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.456,\n",
       "    'neutral': 0.542,\n",
       "    'sadness': 0.001,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': '2689fdb4-9479-41a2-9280-c0160441daa1',\n",
       "  'faceRectangle': {'top': 41, 'left': 676, 'width': 52, 'height': 52},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 23.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': 'db57c0f5-a91f-4447-a54d-a1792e3cff32',\n",
       "  'faceRectangle': {'top': 69, 'left': 445, 'width': 52, 'height': 52},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 21.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': 'a04afc8b-c210-44cf-9c40-eaeb78a5d3c1',\n",
       "  'faceRectangle': {'top': 95, 'left': 238, 'width': 51, 'height': 51},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 17.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.981,\n",
       "    'neutral': 0.019,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': '4d8b8cf6-0f00-430a-9176-5815c10aff74',\n",
       "  'faceRectangle': {'top': 94, 'left': 540, 'width': 48, 'height': 48},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 19.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}}]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "KEY = 'd4059f977ae540cb85963ef89c95599d'  # Replace with a valid Subscription Key here.\n",
    "# Base URL,  Request URL中 符号?以前\n",
    "#。                          eastasia.api.cognitive.microsoft.com  ==》{endpoint}\n",
    "BASE_URL = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect' # 人脸检测\n",
    "\n",
    "# 沿用API的示范代碼，{subscription key}用KEY代入\n",
    "HEADERS = {\n",
    "    # Request headers\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': '{}'.format(KEY), #''  \n",
    "}\n",
    "\n",
    "img_url = 'http://newmedia.nfu.edu.cn/wcy/wp-content/uploads/2018/04/post_20180424__NFU_DoraHacks_imoji%E5%9B%A2%E9%98%9F.jpg'\n",
    "\n",
    "data = {\n",
    "    'url': '{}'.format(img_url),\n",
    "}\n",
    "payload = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'flase',\n",
    "    'returnFaceAttributes': '{}'.format('age,gender,emotion'), \n",
    "}\n",
    "r = requests.post(BASE_URL,data=json.dumps(data),params = payload,headers=HEADERS)\n",
    "r.status_code\n",
    "results = r.json()\n",
    "results\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': 'ba14a02d-2d14-4773-85d3-9bdf7ebaa648',\n",
       "  'faceRectangle': {'top': 118, 'left': 144, 'width': 88, 'height': 88},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 18.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.003,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.813,\n",
       "    'neutral': 0.184,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': '4bf7c0dd-02b1-45ba-a148-7442fdca3344',\n",
       "  'faceRectangle': {'top': 117, 'left': 376, 'width': 64, 'height': 64},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 20.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.001,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.456,\n",
       "    'neutral': 0.542,\n",
       "    'sadness': 0.001,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': '2689fdb4-9479-41a2-9280-c0160441daa1',\n",
       "  'faceRectangle': {'top': 41, 'left': 676, 'width': 52, 'height': 52},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 23.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': 'db57c0f5-a91f-4447-a54d-a1792e3cff32',\n",
       "  'faceRectangle': {'top': 69, 'left': 445, 'width': 52, 'height': 52},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 21.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': 'a04afc8b-c210-44cf-9c40-eaeb78a5d3c1',\n",
       "  'faceRectangle': {'top': 95, 'left': 238, 'width': 51, 'height': 51},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 17.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.981,\n",
       "    'neutral': 0.019,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': '4d8b8cf6-0f00-430a-9176-5815c10aff74',\n",
       "  'faceRectangle': {'top': 94, 'left': 540, 'width': 48, 'height': 48},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 19.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}}]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第三张：多人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': '366e9b48-23c4-4c47-814c-221ccacb52ff',\n",
       "  'faceRectangle': {'top': 367, 'left': 159, 'width': 396, 'height': 396},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 16.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 1.0,\n",
       "    'neutral': 0.0,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': 'd0eacf66-0e5f-4aba-9b6f-0e10bb2ca03e',\n",
       "  'faceRectangle': {'top': 147, 'left': 566, 'width': 244, 'height': 244},\n",
       "  'faceAttributes': {'gender': 'male',\n",
       "   'age': 17.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.001,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.013,\n",
       "    'neutral': 0.986,\n",
       "    'sadness': 0.0,\n",
       "    'surprise': 0.0}}},\n",
       " {'faceId': 'c3ea131d-eee2-4ba9-8294-af74a5855ad1',\n",
       "  'faceRectangle': {'top': 468, 'left': 1016, 'width': 227, 'height': 227},\n",
       "  'faceAttributes': {'gender': 'female',\n",
       "   'age': 18.0,\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.0,\n",
       "    'neutral': 0.998,\n",
       "    'sadness': 0.001,\n",
       "    'surprise': 0.0}}}]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "KEY = 'd4059f977ae540cb85963ef89c95599d'  # Replace with a valid Subscription Key here.\n",
    "# Base URL,  Request URL中 符号?以前\n",
    "#。                          eastasia.api.cognitive.microsoft.com  ==》{endpoint}\n",
    "BASE_URL = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect' # 人脸检测\n",
    "\n",
    "# 沿用API的示范代碼，{subscription key}用KEY代入\n",
    "HEADERS = {\n",
    "    # Request headers\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': '{}'.format(KEY), #''  \n",
    "}\n",
    "\n",
    "img_url = 'http://liuyu19.gitee.io/api/img/11.jpg'\n",
    "\n",
    "data = {\n",
    "    'url': '{}'.format(img_url),\n",
    "}\n",
    "payload = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'flase',\n",
    "    'returnFaceAttributes': '{}'.format('age,gender,emotion'), \n",
    "}\n",
    "r = requests.post(BASE_URL,data=json.dumps(data),params = payload,headers=HEADERS)\n",
    "r.status_code\n",
    "results = r.json()\n",
    "results\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第二家API（Face++)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第一张：单人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1、先导入为们需要的模块\n",
    "import requests\n",
    "\n",
    "\n",
    "api_secret = \"R8i8W3vtgSBsMPjkJY9Y_Cgi8erIXP66\"\n",
    "# 2、输入我们API_Key\n",
    "api_key = 'oHuKvBRLPTWZv4mfCBbj2IGcdyTY7eB6'  # Replace with a valid Subscription Key here.\n",
    "\n",
    "\n",
    "# 3、目标url\n",
    "# 这里也可以使用本地图片 例如：filepath =\"image/tupian.jpg\"\n",
    "BASE_URL = 'https://api-cn.faceplusplus.com/facepp/v3/detect' \n",
    "img_url = 'http://liuyu19.gitee.io/api/img/1.jpg'\n",
    "\n",
    "# 4、沿用API文档的示范代码,准备我们的headers和图片(数据)\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "}\n",
    "\n",
    "# 5、准备symbol ? 后面的数据\n",
    "\n",
    "payload = {\n",
    "    \"image_url\":img_url,\n",
    "    'api_key': api_key,\n",
    "    'api_secret': api_secret,\n",
    "    'return_attributes':'gender,age,smiling,emotion', \n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = requests.post(BASE_URL, params=payload, headers=headers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'{\"request_id\":\"1586938239,e22f1ced-8530-4444-8a18-e786e3916d28\",\"time_used\":614,\"faces\":[{\"face_token\":\"1881b0c2c69f0e1bb300182ea025b219\",\"face_rectangle\":{\"top\":552,\"left\":447,\"width\":323,\"height\":323},\"attributes\":{\"gender\":{\"value\":\"Male\"},\"age\":{\"value\":21},\"smile\":{\"value\":0.001,\"threshold\":50.000},\"emotion\":{\"anger\":0.036,\"disgust\":0.000,\"fear\":0.000,\"happiness\":0.000,\"neutral\":97.994,\"sadness\":1.968,\"surprise\":0.000}}}],\"image_id\":\"Hk0qBnkpX0khw3kMPXYbtQ==\",\"face_num\":1}\\n'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'request_id': '1586938239,e22f1ced-8530-4444-8a18-e786e3916d28',\n",
       " 'time_used': 614,\n",
       " 'faces': [{'face_token': '1881b0c2c69f0e1bb300182ea025b219',\n",
       "   'face_rectangle': {'top': 552, 'left': 447, 'width': 323, 'height': 323},\n",
       "   'attributes': {'gender': {'value': 'Male'},\n",
       "    'age': {'value': 21},\n",
       "    'smile': {'value': 0.001, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.036,\n",
       "     'disgust': 0.0,\n",
       "     'fear': 0.0,\n",
       "     'happiness': 0.0,\n",
       "     'neutral': 97.994,\n",
       "     'sadness': 1.968,\n",
       "     'surprise': 0.0}}}],\n",
       " 'image_id': 'Hk0qBnkpX0khw3kMPXYbtQ==',\n",
       " 'face_num': 1}"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# requests 巧妙的方法   r = response\n",
    "results = r.json() # \n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第二张：多人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'{\"request_id\":\"1586938263,bc87e1c0-90e5-41fe-9cd8-5acb269b0e78\",\"time_used\":308,\"faces\":[{\"face_token\":\"c4ee77f0ee5c8b1f998abb5f590a50c8\",\"face_rectangle\":{\"top\":123,\"left\":138,\"width\":90,\"height\":90},\"attributes\":{\"gender\":{\"value\":\"Male\"},\"age\":{\"value\":23},\"smile\":{\"value\":99.995,\"threshold\":50.000},\"emotion\":{\"anger\":0.059,\"disgust\":0.059,\"fear\":0.059,\"happiness\":42.294,\"neutral\":52.431,\"sadness\":4.920,\"surprise\":0.179}}},{\"face_token\":\"dcf9781096145550156eec874854551d\",\"face_rectangle\":{\"top\":122,\"left\":373,\"width\":65,\"height\":65},\"attributes\":{\"gender\":{\"value\":\"Female\"},\"age\":{\"value\":37},\"smile\":{\"value\":98.866,\"threshold\":50.000},\"emotion\":{\"anger\":0.169,\"disgust\":7.280,\"fear\":0.138,\"happiness\":17.689,\"neutral\":8.067,\"sadness\":66.519,\"surprise\":0.138}}},{\"face_token\":\"2849127688a60bf473fea7aa85f9060c\",\"face_rectangle\":{\"top\":46,\"left\":675,\"width\":54,\"height\":54},\"attributes\":{\"gender\":{\"value\":\"Male\"},\"age\":{\"value\":23},\"smile\":{\"value\":100.000,\"threshold\":50.000},\"emotion\":{\"anger\":0.000,\"disgust\":0.000,\"fear\":0.000,\"happiness\":99.996,\"neutral\":0.001,\"sadness\":0.002,\"surprise\":0.001}}},{\"face_token\":\"5844e7a591d9834ffe07b2ab53a953e1\",\"face_rectangle\":{\"top\":98,\"left\":235,\"width\":53,\"height\":53},\"attributes\":{\"gender\":{\"value\":\"Female\"},\"age\":{\"value\":22},\"smile\":{\"value\":99.997,\"threshold\":50.000},\"emotion\":{\"anger\":0.000,\"disgust\":0.001,\"fear\":0.000,\"happiness\":99.990,\"neutral\":0.009,\"sadness\":0.000,\"surprise\":0.000}}},{\"face_token\":\"16042b5a339f820804e28052fe2b8d96\",\"face_rectangle\":{\"top\":75,\"left\":444,\"width\":52,\"height\":52},\"attributes\":{\"gender\":{\"value\":\"Female\"},\"age\":{\"value\":28},\"smile\":{\"value\":99.999,\"threshold\":50.000},\"emotion\":{\"anger\":0.001,\"disgust\":0.001,\"fear\":0.027,\"happiness\":99.933,\"neutral\":0.027,\"sadness\":0.010,\"surprise\":0.001}}},{\"face_token\":\"f341c7633cad61d8f291556240176f8f\",\"face_rectangle\":{\"top\":98,\"left\":537,\"width\":48,\"height\":48}}],\"image_id\":\"TfC1AByqtXhfuQ6DruqVww==\",\"face_num\":6}\\n'"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1、先导入为们需要的模块\n",
    "import requests\n",
    "\n",
    "\n",
    "api_secret = \"R8i8W3vtgSBsMPjkJY9Y_Cgi8erIXP66\"\n",
    "# 2、输入我们API_Key\n",
    "api_key = 'oHuKvBRLPTWZv4mfCBbj2IGcdyTY7eB6'  # Replace with a valid Subscription Key here.\n",
    "\n",
    "\n",
    "# 3、目标url\n",
    "# 这里也可以使用本地图片 例如：filepath =\"image/tupian.jpg\"\n",
    "BASE_URL = 'https://api-cn.faceplusplus.com/facepp/v3/detect' \n",
    "img_url = 'http://newmedia.nfu.edu.cn/wcy/wp-content/uploads/2018/04/post_20180424__NFU_DoraHacks_imoji%E5%9B%A2%E9%98%9F.jpg'\n",
    "\n",
    "# 4、沿用API文档的示范代码,准备我们的headers和图片(数据)\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "}\n",
    "\n",
    "# 5、准备symbol ? 后面的数据\n",
    "\n",
    "payload = {\n",
    "    \"image_url\":img_url,\n",
    "    'api_key': api_key,\n",
    "    'api_secret': api_secret,\n",
    "    'return_attributes':'gender,age,smiling,emotion', \n",
    "}\n",
    "\n",
    "r = requests.post(BASE_URL, params=payload, headers=headers)\n",
    "r.status_code\n",
    "r.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'request_id': '1586938263,bc87e1c0-90e5-41fe-9cd8-5acb269b0e78',\n",
       " 'time_used': 308,\n",
       " 'faces': [{'face_token': 'c4ee77f0ee5c8b1f998abb5f590a50c8',\n",
       "   'face_rectangle': {'top': 123, 'left': 138, 'width': 90, 'height': 90},\n",
       "   'attributes': {'gender': {'value': 'Male'},\n",
       "    'age': {'value': 23},\n",
       "    'smile': {'value': 99.995, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.059,\n",
       "     'disgust': 0.059,\n",
       "     'fear': 0.059,\n",
       "     'happiness': 42.294,\n",
       "     'neutral': 52.431,\n",
       "     'sadness': 4.92,\n",
       "     'surprise': 0.179}}},\n",
       "  {'face_token': 'dcf9781096145550156eec874854551d',\n",
       "   'face_rectangle': {'top': 122, 'left': 373, 'width': 65, 'height': 65},\n",
       "   'attributes': {'gender': {'value': 'Female'},\n",
       "    'age': {'value': 37},\n",
       "    'smile': {'value': 98.866, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.169,\n",
       "     'disgust': 7.28,\n",
       "     'fear': 0.138,\n",
       "     'happiness': 17.689,\n",
       "     'neutral': 8.067,\n",
       "     'sadness': 66.519,\n",
       "     'surprise': 0.138}}},\n",
       "  {'face_token': '2849127688a60bf473fea7aa85f9060c',\n",
       "   'face_rectangle': {'top': 46, 'left': 675, 'width': 54, 'height': 54},\n",
       "   'attributes': {'gender': {'value': 'Male'},\n",
       "    'age': {'value': 23},\n",
       "    'smile': {'value': 100.0, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.0,\n",
       "     'disgust': 0.0,\n",
       "     'fear': 0.0,\n",
       "     'happiness': 99.996,\n",
       "     'neutral': 0.001,\n",
       "     'sadness': 0.002,\n",
       "     'surprise': 0.001}}},\n",
       "  {'face_token': '5844e7a591d9834ffe07b2ab53a953e1',\n",
       "   'face_rectangle': {'top': 98, 'left': 235, 'width': 53, 'height': 53},\n",
       "   'attributes': {'gender': {'value': 'Female'},\n",
       "    'age': {'value': 22},\n",
       "    'smile': {'value': 99.997, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.0,\n",
       "     'disgust': 0.001,\n",
       "     'fear': 0.0,\n",
       "     'happiness': 99.99,\n",
       "     'neutral': 0.009,\n",
       "     'sadness': 0.0,\n",
       "     'surprise': 0.0}}},\n",
       "  {'face_token': '16042b5a339f820804e28052fe2b8d96',\n",
       "   'face_rectangle': {'top': 75, 'left': 444, 'width': 52, 'height': 52},\n",
       "   'attributes': {'gender': {'value': 'Female'},\n",
       "    'age': {'value': 28},\n",
       "    'smile': {'value': 99.999, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.001,\n",
       "     'disgust': 0.001,\n",
       "     'fear': 0.027,\n",
       "     'happiness': 99.933,\n",
       "     'neutral': 0.027,\n",
       "     'sadness': 0.01,\n",
       "     'surprise': 0.001}}},\n",
       "  {'face_token': 'f341c7633cad61d8f291556240176f8f',\n",
       "   'face_rectangle': {'top': 98, 'left': 537, 'width': 48, 'height': 48}}],\n",
       " 'image_id': 'TfC1AByqtXhfuQ6DruqVww==',\n",
       " 'face_num': 6}"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# requests 巧妙的方法   r = response\n",
    "results = r.json() # \n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第三张：多人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'{\"request_id\":\"1586938298,92674fcb-e660-4e2c-b529-7f64e12b3951\",\"time_used\":523,\"faces\":[{\"face_token\":\"d700c071eb313b526ca523a7013f416d\",\"face_rectangle\":{\"top\":399,\"left\":152,\"width\":394,\"height\":394},\"attributes\":{\"gender\":{\"value\":\"Female\"},\"age\":{\"value\":23},\"smile\":{\"value\":99.999,\"threshold\":50.000},\"emotion\":{\"anger\":0.000,\"disgust\":0.000,\"fear\":0.001,\"happiness\":99.999,\"neutral\":0.000,\"sadness\":0.000,\"surprise\":0.000}}},{\"face_token\":\"7d806d37595db8559f016beb0a9b1bb4\",\"face_rectangle\":{\"top\":164,\"left\":552,\"width\":244,\"height\":244},\"attributes\":{\"gender\":{\"value\":\"Male\"},\"age\":{\"value\":21},\"smile\":{\"value\":0.091,\"threshold\":50.000},\"emotion\":{\"anger\":0.187,\"disgust\":0.015,\"fear\":0.015,\"happiness\":32.740,\"neutral\":66.896,\"sadness\":0.021,\"surprise\":0.127}}},{\"face_token\":\"70b6b8313e63d577cd4d7d9d6b4a6b50\",\"face_rectangle\":{\"top\":475,\"left\":1012,\"width\":226,\"height\":226},\"attributes\":{\"gender\":{\"value\":\"Female\"},\"age\":{\"value\":23},\"smile\":{\"value\":0.225,\"threshold\":50.000},\"emotion\":{\"anger\":0.208,\"disgust\":0.049,\"fear\":0.049,\"happiness\":0.049,\"neutral\":17.257,\"sadness\":51.440,\"surprise\":30.949}}}],\"image_id\":\"tz1Z/oc9WqSKtd3SooXDig==\",\"face_num\":3}\\n'"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1、先导入为们需要的模块\n",
    "import requests\n",
    "\n",
    "\n",
    "api_secret = \"R8i8W3vtgSBsMPjkJY9Y_Cgi8erIXP66\"\n",
    "# 2、输入我们API_Key\n",
    "api_key = 'oHuKvBRLPTWZv4mfCBbj2IGcdyTY7eB6'  # Replace with a valid Subscription Key here.\n",
    "\n",
    "\n",
    "# 3、目标url\n",
    "# 这里也可以使用本地图片 例如：filepath =\"image/tupian.jpg\"\n",
    "BASE_URL = 'https://api-cn.faceplusplus.com/facepp/v3/detect' \n",
    "img_url = 'http://liuyu19.gitee.io/api/img/11.jpg'\n",
    "\n",
    "# 4、沿用API文档的示范代码,准备我们的headers和图片(数据)\n",
    "\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "}\n",
    "\n",
    "# 5、准备symbol ? 后面的数据\n",
    "\n",
    "payload = {\n",
    "    \"image_url\":img_url,\n",
    "    'api_key': api_key,\n",
    "    'api_secret': api_secret,\n",
    "    'return_attributes':'gender,age,smiling,emotion', \n",
    "}\n",
    "\n",
    "r = requests.post(BASE_URL, params=payload, headers=headers)\n",
    "r.status_code\n",
    "r.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'request_id': '1586938298,92674fcb-e660-4e2c-b529-7f64e12b3951',\n",
       " 'time_used': 523,\n",
       " 'faces': [{'face_token': 'd700c071eb313b526ca523a7013f416d',\n",
       "   'face_rectangle': {'top': 399, 'left': 152, 'width': 394, 'height': 394},\n",
       "   'attributes': {'gender': {'value': 'Female'},\n",
       "    'age': {'value': 23},\n",
       "    'smile': {'value': 99.999, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.0,\n",
       "     'disgust': 0.0,\n",
       "     'fear': 0.001,\n",
       "     'happiness': 99.999,\n",
       "     'neutral': 0.0,\n",
       "     'sadness': 0.0,\n",
       "     'surprise': 0.0}}},\n",
       "  {'face_token': '7d806d37595db8559f016beb0a9b1bb4',\n",
       "   'face_rectangle': {'top': 164, 'left': 552, 'width': 244, 'height': 244},\n",
       "   'attributes': {'gender': {'value': 'Male'},\n",
       "    'age': {'value': 21},\n",
       "    'smile': {'value': 0.091, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.187,\n",
       "     'disgust': 0.015,\n",
       "     'fear': 0.015,\n",
       "     'happiness': 32.74,\n",
       "     'neutral': 66.896,\n",
       "     'sadness': 0.021,\n",
       "     'surprise': 0.127}}},\n",
       "  {'face_token': '70b6b8313e63d577cd4d7d9d6b4a6b50',\n",
       "   'face_rectangle': {'top': 475, 'left': 1012, 'width': 226, 'height': 226},\n",
       "   'attributes': {'gender': {'value': 'Female'},\n",
       "    'age': {'value': 23},\n",
       "    'smile': {'value': 0.225, 'threshold': 50.0},\n",
       "    'emotion': {'anger': 0.208,\n",
       "     'disgust': 0.049,\n",
       "     'fear': 0.049,\n",
       "     'happiness': 0.049,\n",
       "     'neutral': 17.257,\n",
       "     'sadness': 51.44,\n",
       "     'surprise': 30.949}}}],\n",
       " 'image_id': 'tz1Z/oc9WqSKtd3SooXDig==',\n",
       " 'face_num': 3}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# requests 巧妙的方法   r = response\n",
    "results = r.json() # \n",
    "results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第三家API（腾讯云)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第一张：单人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib  \n",
    "import time  \n",
    "import random  \n",
    "import string\n",
    "import requests  \n",
    "import base64  \n",
    "import requests\n",
    "# import cv2\n",
    "import numpy as np\n",
    "from urllib.parse import urlencode\n",
    "import json #用于post后得到的字符串到字典的转换\n",
    "\n",
    "app_id = '1106649312' \n",
    "app_key = 'TwsQQv5G5c9E6FsH'\n",
    "\n",
    "# \n",
    "       # 腾讯openai鉴权签名计算步骤：（摘抄自官网）\n",
    "            #用于计算签名的参数在不同接口之间会有差异，但算法过程固定如下4个步骤。\n",
    "       # 1 将<key, value>请求参数对按key进行字典升序排序，得到有序的参数对列表N\n",
    "        #2 将列表N中的参数对按URL键值对的格式拼接成字符串，得到字符串T（如：key1=value1&key2=value2），URL键值拼接过程value部分需要URL编码，URL编码算法用大写字母，例如%E8，而不是小写%e8\n",
    "       # 3 将应用密钥以app_key为键名，组成URL键值拼接到字符串T末尾，得到字符串S（如：key1=value1&key2=value2&app_key=密钥)\n",
    "        #4 对字符串S进行MD5运算，将得到的MD5值所有字符转换成大写，得到接口请求签名\n",
    "#\n",
    "def get_params(img):                         #鉴权计算并返回请求参数\n",
    "    #请求时间戳（秒级），用于防止请求重放（保证签名5分钟有效\n",
    "    time_stamp=str(int(time.time())) \n",
    "    #请求随机字符串，用于保证签名不可预测,16代表16位\n",
    "    nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))\n",
    "\n",
    "    params = {'app_id':app_id,                #请求包，需要根据不同的任务修改，基本相同\n",
    "              'image':img,                    #文字类的任务可能是‘text’，由主函数传递进来\n",
    "              'mode':'0' ,                    #身份证件类可能是'card_type'\n",
    "              'time_stamp':time_stamp,        #时间戳，都一样\n",
    "              'nonce_str':nonce_str,          #随机字符串，都一样\n",
    "              #'sign':''                      #签名不参与鉴权计算，只是列出来示意\n",
    "             }\n",
    "\n",
    "    sort_dict= sorted(params.items(), key=lambda item:item[0], reverse = False)  #字典排序\n",
    "    sort_dict.append(('app_key',app_key))   #尾部添加appkey\n",
    "    rawtext= urlencode(sort_dict).encode()  #urlencod编码\n",
    "    sha = hashlib.md5()    \n",
    "    sha.update(rawtext)\n",
    "    md5text= sha.hexdigest().upper()        #MD5加密计算\n",
    "    params['sign']=md5text                  #将签名赋值到sign\n",
    "    return  params                          #返回请求包\n",
    "\n",
    "with open(r\"C:\\Users\\84911\\Desktop\\api\\img\\1.jpg\",\"rb\")as f:\n",
    "    base64_data = base64.b64encode(f.read())   #得到API可以识别的字符串\n",
    "    \n",
    "    params = get_params(base64_data)    #获取鉴权签名并获取请求参数\n",
    "\n",
    "    url = \"https://api.ai.qq.com/fcgi-bin/face/face_detectface\"  # 人脸分析\n",
    "    #检测给定图片（Image）中的所有人脸（Face）的位置和相应的面部属性。位置包括（x, y, w, h），面部属性包括性别（gender）, 年龄（age）, 表情（expression）, 魅力（beauty）, 眼镜（glass）和姿态（pitch，roll，yaw）  \n",
    "    res = requests.post(url,params).json()\n",
    "    res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 总结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在我看来，AZURE家的人脸识别使用简单，文档可读性强，而且识别出来的年龄相差不大，相比之下Face++功能同样强大，但在女性年龄测试方面会受到妆容等因素的影响，偏大2-3岁。腾讯云我真的是无力吐槽，文档可读性低，操作复杂，功能也不够全面，任重道远啊。且腾讯云识别不了多人。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "303.837px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
